package com.gientech.esexercise.controller;

import com.gientech.esexercise.entity.TestUser;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.HashMap;

@SuppressWarnings("SpringJavaAutowiringInspection")
@RestController
public class TestUserController {

    @Resource
    private ElasticsearchRestTemplate elasticsearchRestTemplate;

    @GetMapping("/save")
    public String save(){

        TestUser user = new TestUser();
        user.setId("1");
        user.setName("小张");
        user.setAge(18);
        user.setSex("Male");
        user.setPhone("123456789");

        //indexName默认取@Document中的indexName
        elasticsearchRestTemplate.save(user);

        //indexName动态制定--索引如果不存在save会自动创建后再存入数据
        elasticsearchRestTemplate.save(user, IndexCoordinates.of("test_user_info"));

        elasticsearchRestTemplate.save(user, IndexCoordinates.of("test_user_info_dd"));

        return "succ";
    }

    @GetMapping("/search")
    public Object search(){
        BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
        NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder();
        builder.withQuery(queryBuilder);
        NativeSearchQuery build = builder.build();

        SearchHits<TestUser> user = elasticsearchRestTemplate.search(build , TestUser.class);

        //indexName动态指定
        SearchHits<TestUser> user_info = elasticsearchRestTemplate.search(build , TestUser.class ,IndexCoordinates.of("test_user_info"));

        HashMap<Object, Object> objectHashMap = new HashMap<Object, Object>();
        objectHashMap.put("test_user", user.getSearchHits());
        objectHashMap.put("test_user_info", user_info.getSearchHits());

        return objectHashMap;
    }

    @GetMapping("/delete")
    public String delete(){

        //根据ID删除-indexName默认取@Document中indexName
        elasticsearchRestTemplate.delete("1", TestUser.class);

        //根据ID删除-indexName动态指定
        elasticsearchRestTemplate.delete("1", IndexCoordinates.of("test_user_info"));

        return "delete succ";
    }


}
